<template>
  <div>
    <Select
      v-bind="$attrs"
      v-model:value="value"
      style="width: 100%"
      :options="data"
      :fieldNames="{ label: 'dbName', value: 'id' }"
      :placeholder="placeholder"
      @change="handleChange"
    >
      <template #dropdownRender="{ menuNode: menu }">
        <component :is="menu" />
        <Divider style="margin: 4px 0" />
        <div
          style="padding: 4px 8px; cursor: pointer"
          @mousedown="(e) => e.preventDefault()"
          @click="add"
        >
          <PlusOutlined />
          {{ t('新增') }}
        </div>
      </template>
    </Select>
    <DatabaseLinkDrawer @register="registerDbDrawer" @success="handleDetailSuccess" />
  </div>
</template>
<script lang="ts" setup>
  import { Select, Divider } from 'ant-design-vue';
  import { PlusOutlined } from '@ant-design/icons-vue';
  import { onMounted, ref, unref, watch } from 'vue';
  import { getDatabaselinkTree } from '/@/api/system/databaselink';
  import DatabaseLinkDrawer from '../components/DatabaseLinkDrawer.vue';
  import { TreeItem } from '/@/components/Tree';
  import { useDrawer } from '../../Drawer';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { isNil } from 'lodash-es';

  const { t } = useI18n();
  const emit = defineEmits(['change']);

  const props = defineProps({
    value: String,
    placeholder: String,
  });

  const value = ref();

  const data = ref<Recordable[]>([]);

  onMounted(() => {
    fetch();
  });

  const handleChange = async (value, option?) => {
    if (!option) {
      if (!data.value.length) await fetch();
      const selectData = data.value.filter((item) => item.id === value);
      option = selectData.length ? selectData[0] : null;
    }
    emit('change', value, option);
  };

  watch(
    () => props.value,
    (val) => {
      value.value = val;
      if (!isNil(val)) {
        handleChange(unref(value));
      }
    },
    {
      immediate: true,
    },
  );

  async function fetch() {
    data.value = ((await getDatabaselinkTree()) as unknown as TreeItem[]) || [];
  }

  const [registerDbDrawer, { openDrawer }] = useDrawer();

  const add = () => {
    openDrawer(true);
  };

  const handleDetailSuccess = () => {
    fetch();
  };
</script>
